package com.wispx.gateway.core.filter.cors;

import com.wispx.gateway.core.context.GatewayContext;
import com.wispx.gateway.core.filter.Filter;
import com.wispx.gateway.core.helper.GatewayContextHelper;
import com.wispx.gateway.core.helper.GatewayResponseHelper;
import com.wispx.gateway.core.response.GatewayResponse;
import io.netty.handler.codec.http.HttpMethod;

import static com.wispx.gateway.common.constant.FilterConstant.CORS_FILTER_NAME;
import static com.wispx.gateway.common.constant.FilterConstant.CORS_FILTER_ORDER;

public class CorsFilter implements Filter {
    @Override
    public void doPreFilter(GatewayContext ctx) {
        if (HttpMethod.OPTIONS.equals(ctx.getRequest().getMethod())) {// 复杂请求，浏览器会先发送 OPTIONS请求 检查权限
            ctx.setResponse(GatewayResponseHelper.bulidGatewayResponse());
            GatewayContextHelper.writeBack2Client(ctx);
        } else {
            ctx.doFilter();
        }
    }

    @Override
    public void doPostFilter(GatewayContext ctx) {
        GatewayResponse gatewayResponse = ctx.getResponse();
        gatewayResponse.addHeader("Access-Control-Allow-Origin", "*"); // 允许哪些源（域名）可以访问资源
        gatewayResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS"); // 允许的 HTTP 方法
        gatewayResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,Authorization"); // 允许的请求头
        gatewayResponse.addHeader("Access-Control-Allow-Credentials", "true"); // 是否允许发送凭据（cookies、HTTP认证等）
        ctx.doFilter();
    }

    @Override
    public String mark() {
        return CORS_FILTER_NAME;
    }

    @Override
    public int getOrder() {
        return CORS_FILTER_ORDER;
    }
}
